package com.quickcode.example.concurrent;

import com.quickcode.annotation.Safe;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.*;

/**
 * Created by 张波 on 2019/10/24.
 */
@Slf4j
@Safe
public class CopyOnWriteArrayListExample {

    public static final int clientTotal = 5000;

    public static final int threadTotal = 200;

    public static List<Integer> list = new CopyOnWriteArrayList<>();

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0 ; i < clientTotal ; i++) {
            final int count = 1;
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    add(count);
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("exception:{}",e);
                }
                countDownLatch.countDown();
            });
        }
        try {
            log.info("开始进入线程等待");
            countDownLatch.await();
        } catch (InterruptedException e) {
            log.error("exception:{}",e);
        }
        executorService.shutdown();
        log.error("最终结果length：{}", list.size());
    }

    private static void add(int i) {
        list.add(i);
    }

}
